package com.aaa.dao.impl;

import com.aaa.dao.BaseDao;
import com.aaa.dao.MenuDao;
import com.aaa.entity.Pager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MenuDaoImpl extends BaseDao implements MenuDao {
    @Override
    public Pager query(int curPage, int pageSize, Map condition) {
        String sql="select * from sys_menu where 1=1 ";
        StringBuffer buffer=new StringBuffer(sql);
        List params=new ArrayList();

        if (condition!=null)
        {
            if (condition.containsKey("menu_name")&&condition.get("menu_name").toString().length()>0)
            {
                buffer.append("and menu_name like ?");
                params.add("%"+condition.get("menu_name")+"%");
            }
            if (condition.containsKey("parent_id")&&condition.get("parent_id").toString().length()>0)
            {
                buffer.append("and parent_id like ?");
                params.add("%"+condition.get("parent_id")+"%");
            }
        }

        sql="select count(*) c from ("+buffer+") menu";
        List<Map> map=this.executeQuery(sql,params.toArray());
        Long count=(long)map.get(0).get("c");

        buffer.append("limit ?,?");
        int startIndex=(curPage-1)*pageSize;
        params.add(startIndex);
        params.add(pageSize);
        List<Map> list=this.executeQuery(buffer.toString(),params.toArray());

        Pager pager=new Pager(curPage,pageSize,list,count.intValue());
        return pager;

    }

    @Override
    public List queryMenuByUserId(int userid) {
        String sql="select m.menu_id id,m.menu_name text,m.icon,m.url from sys_user_role ur,sys_role_menu rm,sys_menu m WHERE ur.role_id=rm.role_id AND rm.menu_id=m.menu_id AND ur.user_id=? AND m.parent_id=?";
        List firstMenus=this.executeQuery(sql,userid,0);
        for (int i=0;i<firstMenus.size();i++)
        {
            Map<String,Object> firstMenu= (Map<String, Object>) firstMenus.get(i);
            Object id=firstMenu.get("id");
            List secondmenus=this.executeQuery(sql,userid,id);
            if (secondmenus.size()>0)
            {
                firstMenu.put("menus",secondmenus);
            }
        }
        return firstMenus;
    }


}
